package com.jt.controller;

import com.jt.pojo.User;
import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//@CrossOrigin("http://baidu.com")    //只允许百度进行访问.
@CrossOrigin    //任意网址都可以跨域访问
public class UserController {

    @Autowired
    private UserService userService;

    //需求:利用MP查询demo_user全部数据 /findAll
    @RequestMapping("/findAll")
    public List<User> findAll() {

        return userService.findAll();
    }

    @GetMapping("/getUserById/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @GetMapping("/getUserByNS")
    public List<User> getByUS(User us) {
        return userService.getByUs(us);
    }

    //查询带君的数据
    @GetMapping("/user/{name}")
    public List<User> getUser(@PathVariable String name) {
        return userService.getUser(name);
    }

    //删除指定对象的数据
    @DeleteMapping("/removeUser")
    public int removeUser(User user) {
        return userService.removeuser(user);
    }

    //删除指定对象的数据 restful方式
    @DeleteMapping("/user/{name}/{sex}")
    public int removeNS(@PathVariable String name,
                        @PathVariable String sex) {
        return userService.removeNS(name, sex);
    }

    @DeleteMapping("/deleteById/{id}")
    public int deleteById(@PathVariable int id) {
        return userService.deleteById(id);
    }

    /**
     * URL: http://LocaZhost:8090/saveUser
     * 参数:对象的JSON串，{key:value}
     * 类型: POST
     * 返回值: String
     * 难点:如何将JSON 串转化为User对象!
     * SpringMVC:针对于JSON与对象转化开发2个注解
     * 1. @ResponseBody将对象转化为JSON串
     * 2. @RequestBody将JSON 串转化为User对象
     */

    @PostMapping("/saveUser")
    public String saveUser(@RequestBody User user){
        System.out.println(user);
        userService.saveUser(user);
        return "新增数据成功";
    }

    @PutMapping("/updateByUser")
    public String updateByUser(@RequestBody User user){
        System.out.println(user);
        userService.updateByUser(user);
        return "数据修改成功";
    }

}
